package com.epoch.platform.oss.cloud;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.epoch.base.exception.BusinessException;
import com.jfinal.kit.PropKit;
/**
 * 
* <p>Title: AliyunCloudStorageService.java</p>  
* <p>Description: </p>  
* @author 张清磊
* @QQ 544188838
* @date 2018年9月15日
 */
public class AliyunCloudStorageService extends CloudStorageService {

	private OSS client;
	
	private static String aliyunDomain = PropKit.use("application.properties").get("aliyunDomain");
	private static String aliyunPrefix = PropKit.use("application.properties").get("aliyunPrefix");

	public AliyunCloudStorageService() {
		// 初始化
		init();
	}

	private void init() {
		client = new OSSClientBuilder().build(PropKit.use("application.properties").get("aliyunEndPoint"), 
				PropKit.use("application.properties").get("aliyunAccessKeyId"),PropKit.use("application.properties").get("aliyunAccessKeySecret"));
	}

	@Override
	public String upload(File file, String path) {
		try {
			InputStream inputStream = new FileInputStream(file);
			upload(inputStream, path);
		} catch (FileNotFoundException e) {
			throw new BusinessException("上传文件失败", e);
		}
		return null;
	}
	
	@Override
	public String uploadSuffix(File file, String suffix) {
		try {
			InputStream inputStream = new FileInputStream(file);
			uploadSuffix(inputStream, suffix);
		} catch (FileNotFoundException e) {
			throw new BusinessException("上传文件失败", e);
		}
		return null;
	}

	@Override
	public String upload(byte[] data, String path) {
		return upload(new ByteArrayInputStream(data), path);
	}

	@Override
	public String uploadSuffix(byte[] data, String suffix) {
		return upload(data, getPath(aliyunPrefix, suffix));
	}

	@Override
	public String upload(InputStream inputStream, String path) {
		try {
			client.putObject(PropKit.use("application.properties").get("aliyunBucketName"), path, inputStream);
		} catch (Exception e) {
			throw new BusinessException("上传文件失败，请检查配置信息", e);
		}
		return aliyunDomain+path;
		
	}

	@Override
	public String uploadSuffix(InputStream inputStream, String suffix) {
		return upload(inputStream, getPath(aliyunPrefix, suffix));
	}

	@Override
	public String upload(File file) {
		String fileName = file.getName();
		String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
		InputStream inputStream;
		try {
			inputStream = new FileInputStream(file);
			return upload(inputStream, getPath(aliyunPrefix)+ "." + prefix);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return "";
	}

	

}
